package com.ziyi.tiantianshuiyin;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.gtdev5.geetolsdk.mylibrary.beans.ResultBean;
import com.gtdev5.geetolsdk.mylibrary.beans.UpdateBean;
import com.gtdev5.geetolsdk.mylibrary.callback.BaseCallback;
import com.gtdev5.geetolsdk.mylibrary.contants.Contants;
import com.gtdev5.geetolsdk.mylibrary.http.HttpUtils;
import com.gtdev5.geetolsdk.mylibrary.util.DataSaveUtils;
import com.gtdev5.geetolsdk.mylibrary.util.DeviceUtils;
import com.gtdev5.geetolsdk.mylibrary.util.SpUtils;
import com.gtdev5.geetolsdk.mylibrary.util.Utils;
import com.gtdev5.geetolsdk.mylibrary.widget.CenterDialog;
import com.ziyi.tiantianshuiyin.util.AgreementDialog;
import com.ziyi.tiantianshuiyin.util.AppConfig;
import com.ziyi.tiantianshuiyin.util.MyAppUtil;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Request;
import okhttp3.Response;

import static com.gtdev5.geetolsdk.mylibrary.util.DeviceUtils.GEETOL_DEVICE_ID;

public class NewWelcomeActivity extends AppCompatActivity {
    @BindView(R.id.splash_holder)
    ImageView splashHolder;
    @BindView(R.id.launcher_splash)
    FrameLayout launcher_splash;
    private AgreementDialog mDialog1;//首次弹窗
    private AgreementDialog mDialog2;//第二次弹窗
    private boolean isFirstRegister; // 是否首次注册

    //广告对象
//    private TTBannerAdUtil mAdUtils;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);
        if (Utils.isEmpty(DeviceUtils.getSpDeviceId())) {
            // 没有设备id
            String uuid = DeviceUtils.getUUID();
            SpUtils.getInstance().putString(GEETOL_DEVICE_ID, uuid);
        }
        isFirstRegister = SpUtils.getInstance().getBoolean(Contants.FIRST_REGISTER, true);
        boolean isAgree = SpUtils.getInstance().getBoolean(AppConfig.IS_CONFIRM_USER_AGREEMENT, false);//是否同意用户协议
        if (!isAgree) {
            // 还未同意过协议
            showDialog1();
        } else {
            // 同意协议
            setData();
        }
    }

    /**
     * 处理数据
     */
    private void setData() {
        if (isFirstRegister) {
            registerId();
        } else {
            getUpdateInfo();
        }
    }

    /**
     * 跳转到下个页面
     */
    private void goToNext() {
        //通过条件显示广告
//        if (TTBannerAdUtil.isAdSwtOpen()) {
//            try {
//                mAdUtils = new TTBannerAdUtil(this);
//                mAdUtils.loadSplashAd(launcher_splash);
//                mAdUtils.setOnJumpToNext(() -> {
//                    jump(0L);
//                });
//            } catch (Exception e) {
//                e.printStackTrace();
//                // 初始化广告sdk
//                //初始化穿山甲广告创建
//                ExecuteTaskManager.getInstance().init();
//                TTAdManagerHolder.init(this);
//                mAdUtils = new TTBannerAdUtil(this);
//                mAdUtils.loadSplashAd(launcher_splash);
//                mAdUtils.setOnJumpToNext(() -> {
//                    jump(0L);
//                });
//            }
//        } else {
            jump(1500L);
//        }
    }

    private void jump(long time) {
            new Handler().postDelayed(() -> {
                startActivity(new Intent(NewWelcomeActivity.this, MainActivity.class));
                finish();
            }, time);
    }

    /**
     * 注册设备id
     */
    private void registerId() {
        if (Utils.isNetworkAvailable(this)) {
            HttpUtils.getInstance().postRegister(new BaseCallback<ResultBean>() {
                @Override
                public void onRequestBefore() {
                }

                @Override
                public void onFailure(Request request, Exception e) {
                    showRestartDialog();
                }

                @Override
                public void onSuccess(Response response, ResultBean o) {
                    if (o != null) {
                        if (o.isIssucc()) {
                            // 注册成功，调取App数据接口
                            getUpdateInfo();
                            SpUtils.getInstance().putBoolean(Contants.FIRST_REGISTER, false);
                        } else {
                            // 注册失败，弹出提示
                            if (Utils.isNotEmpty(o.getMsg())) {
                                MyAppUtil.showCenterToast(o.getMsg());
                            }
                        }
                    }
                }

                @Override
                public void onError(Response response, int errorCode, Exception e) {
                    showRestartDialog();
                }
            });
        } else {
            showRestartDialog();
        }
    }



    /**
     * 获取应用信息
     */
    private void getUpdateInfo() {
        UpdateBean updateBean = DataSaveUtils.getInstance().getUpdate();
        if (Utils.isNetworkAvailable(this)) {
            HttpUtils.getInstance().postUpdate(new BaseCallback<UpdateBean>() {
                @Override
                public void onRequestBefore() {
                }

                @Override
                public void onFailure(Request request, Exception e) {
                    if (updateBean != null) {
                        goToNext();
                        return;
                    }
                    showRestartDialog();
                }

                @Override
                public void onSuccess(Response response, UpdateBean o) {
                    if (o != null && o.getIssucc()) {
                        // 数据获取成功跳转到下个页面
                        goToNext();
                    } else {
                        // 更新失败，弹出提示
                        if (o != null && Utils.isNotEmpty(o.getMsg())) {
                            MyAppUtil.showCenterToast(o.getMsg());
                        }
                    }
                }

                @Override
                public void onError(Response response, int errorCode, Exception e) {
                    if (updateBean != null) {
                        goToNext();
                        return;
                    }
                    showRestartDialog();
                }
            });
        } else {
            if (updateBean != null) {
                goToNext();
                return;
            }
            showRestartDialog();
        }
        checkLogin();
    }

    /**
     * 校验登陆
     */
    private void checkLogin() {
        if (Utils.isNetworkAvailable(this)) {
            if (!TextUtils.isEmpty(Utils.getUserId())) {
                // 登录过
                HttpUtils.getInstance().checkLogin(new BaseCallback<ResultBean>() {
                    @Override
                    public void onRequestBefore() {
                    }

                    @Override
                    public void onFailure(Request request, Exception e) {
                    }

                    @Override
                    public void onSuccess(Response response, ResultBean o) {
                        if (o != null) {
                            if (o.isIssucc()) {
                                Log.e("校验登录:", "已经登录过");
                            } else {
                                if (Utils.isNotEmpty(o.getMsg())) {
                                    MyAppUtil.showCenterToast(o.getMsg());
                                }
                                Log.e("校验登录:", "已在别机登录，本机下线");
                            }
                        }
                    }

                    @Override
                    public void onError(Response response, int errorCode, Exception e) {
                    }
                });
            }
        }
    }



    /**
     * 首次弹窗
     */
    private void showDialog1() {
        if (mDialog1 == null) {
            mDialog1 = new AgreementDialog(this, new AgreementDialog.onDialogClickListener() {
                @Override
                public void onConfirm() {
                    setData();
                }

                @Override
                public void onCancel() {
                    // 进第二次弹窗
                    showDialog2();
                }
            });
        }
        if (!mDialog1.isShowing() && !isFinishing()) {
            mDialog1.show();
        }
    }

    /**
     * 第二次弹窗
     */
    private void showDialog2() {
        if (mDialog2 == null) {
            mDialog2 = new AgreementDialog(this, new AgreementDialog.onDialogClickListener() {
                @Override
                public void onConfirm() {
                    // 弹第一次弹窗
                    showDialog1();
                }

                @Override
                public void onCancel() {
                    // 关闭应用
                    finish();
                }
            });
        }
        if (!mDialog2.isShowing() && !isFinishing()) {
            mDialog2.show();
            mDialog2.setButtonText("退出软件", "查看协议",
                    false, "若您不同意《用户协议》和《隐私政策》，我们将无法为您提供产品和服务，非常抱歉。");
        }
    }

    /**
     * 提示网络问题重启应用弹框
     */
    public void showRestartDialog() {
        int[] ids = new int[]{R.id.dialog_bt_ok};
        CenterDialog dialog = new CenterDialog(this, R.layout.gt_dialog_restart_app, ids, false);
        dialog.setOnCenterClickListener((dial, view) -> {
            if (view.getId() == R.id.dialog_bt_ok) {
                if (!isFinishing()) {
                    dialog.dismiss();
                }
                finish();
            }
        });
        if (!isFinishing()) {
            dialog.show();
            dialog.setCanceledOnTouchOutside(false);
            dialog.setCancelable(false);
        }
    }
}
